﻿#region Copyright (c) Lokad 2010
// This code is released under the terms of the new BSD licence.
// URL: http://www.lokad.com/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using Lokad.Monitoring.Persistence.Entities;
using NHibernate.Linq;

namespace Lokad.Monitoring.Persistence.Repositories
{
    public class EndpointRepository : BaseRepository
    {
        public IEnumerable<Endpoint> List()
        {
            return
                (from e in Session.Linq<Endpoint>() 
                 orderby e.Id
                 select e).ToList();
        }
        
        public void Create(Endpoint endpoint)
        {
            using (var trans = Session.BeginTransaction())
            {
                endpoint.LastRetrieved = new DateTime(2001,1,1);
                Session.Save(endpoint);
                trans.Commit();
            }
        }

        public Endpoint Edit(string id)
        {
            return Session.Get<Endpoint>(id);
        }

        public void Edit(string id, Endpoint endpoint)
        {
            using (var trans = Session.BeginTransaction())
            {
                var db = Session.Get<Endpoint>(id);

                db.Frequency = endpoint.Frequency;
                db.Url = endpoint.Url;

                Session.Update(db);
                trans.Commit();
            }
        }

        public void UpdateLastRetrieved(string id)
        {
            using (var trans = Session.BeginTransaction())
            {
                var db = Session.Get<Endpoint>(id);

                db.LastRetrieved = DateTime.UtcNow;

                Session.Update(db);
                trans.Commit();
            }
        }

        public void Delete(string id)
        {
            using (var trans = Session.BeginTransaction())
            {
                var db = Session.Get<Endpoint>(id);
                Session.Delete(db);
                trans.Commit();
            }
        }
    }
}
